<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>医院管理</el-breadcrumb-item>
      <el-breadcrumb-item>药品管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索区 -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        :model="queryInfo.query"
        size="mini"
      >
        <el-form-item label="药品分类【ID】" prop="category">
          <el-select
            v-model="queryInfo.query.category"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in selectData.get_drug_category"
              :key="item.id"
              :label="item.name + '【' + item.id + '】'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品名称【ID】" prop="id">
          <el-select
            v-model="queryInfo.query.id"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in selectData.get_drdrug"
              :key="item.id"
              :label="item.name + '【' + item.id + '】'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            class="theme-background-color"
            size="mini"
            @click="searchList"
          >
            搜索
          </el-button>
          <el-button size="mini" @click="resetSearchForm"> 重置 </el-button>
        </el-form-item>
      </el-form>

      <!-- 操作区域 -->
      <div>
        <el-button
          class="theme-background-color"
          icon="el-icon-first-aid-kit"
          size="mini"
          @click="$router.push('/hospital/DrugsAdd')"
        >
          新增药品
        </el-button>
        <el-button
          class="theme-background-color"
          icon="el-icon-menu"
          size="mini"
          @click="classifyFormialogVisible = true"
        >
          新增分类
        </el-button>
        <el-button
          icon="el-icon-download"
          size="mini"
          :loading="btnLoading"
          @click="downloadExcel"
        >
          导出数据
        </el-button>
        <el-button
          icon="el-icon-upload2"
          size="mini"
          @click="drugImportDialogVisible = true"
          type="primary"
        >
          药品导入
        </el-button>
      </div>

      <!-- 用户列表区域 -->
      <el-table :data="list" border stripe>
        <!-- <el-table-column label="序号" type="index"></el-table-column> -->
        <el-table-column
          label="药品名称【ID】"
          min-width="150px"
          max-width="300px"
        >
          <template slot-scope="scope">
            {{ scope.row.title }}【{{ scope.row.id }}】
          </template>
        </el-table-column>
        <el-table-column label="所属分类【ID】">
          <template slot-scope="scope">
            {{ scope.row.category_name }}【{{ scope.row.category }}】
          </template>
        </el-table-column>
        <el-table-column label="规格【ID】" prop="spec"></el-table-column>
        <el-table-column label="状态" prop="status.name"></el-table-column>
        <el-table-column label="创建人【ID】">
          <template slot-scope="scope">
            {{ scope.row.create_name }}【{{ scope.row.create_id }}】
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="create_time"></el-table-column>
        <el-table-column label="操作" width="90px">
          <template slot-scope="scope">
            <el-link
              type="danger"
              v-if="scope.row.status.id == 1"
              @click="disable(scope.row)"
            >
              关闭
            </el-link>
            <el-link
              type="primary"
              v-if="scope.row.status.id == 0"
              @click="enable(scope.row.id)"
            >
              开启
            </el-link>
            <!-- <el-link type="primary" @click="showLog(scope.row.id)">
              操作记录
            </el-link> -->
            &nbsp;
            <el-link
              type="primary"
              @click="
                $router.push({
                  path: '/hospital/DrugsAdd',
                  query: scope.row
                })
              "
            >
              编辑
            </el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <el-dialog title="新增分类" :visible.sync="classifyFormialogVisible">
        <el-form
          :model="classifyForm"
          ref="classifyFormRef"
          :rules="classifyFormRules"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="分类名称" prop="title">
            <el-input
              v-model="classifyForm.title"
              autocomplete="off"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="classifyForm.remark"
              autocomplete="off"
              show-word-limit
              maxlength="500"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="classifyFormialogVisible = false">取 消</el-button>
          <el-button class="theme-background-color" @click="addClassify"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <!-- <el-dialog title="操作记录" :visible.sync="logDialogVisible" width="60%">
        <el-table :data="logTableData" border>
          <el-table-column
            prop="create_time"
            label="操作时间"
          ></el-table-column>
          <el-table-column
            prop="op_type.name"
            label="操作类型"
          ></el-table-column>
          <el-table-column prop="op_info" label="操作内容"></el-table-column>
          <el-table-column label="操作人【ID】">
            <template slot-scope="scope">
              {{ scope.row.op_uname }}【{{ scope.row.op_uid }}】
            </template>
          </el-table-column>
        </el-table>
      </el-dialog> -->

      <el-dialog
        title="药品导入"
        :visible.sync="drugImportDialogVisible"
        width="40%"
      >
        <div>
          <el-upload
            class="upload-demo"
            ref="upload"
            action="#"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="fileChange"
            :before-upload="beforeUploadFile"
            :multiple="false"
            :limit="1"
            :on-remove="fileRemove"
            :http-request="uploadHttpRequest"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="importExcel"
              :disabled="uploadDisabled"
              >上传到服务器</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="downloadDrugTemplate"
            >
              下载模板
            </el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传xlsx文件，且不超过10M
            </div>
          </el-upload>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: {
          category: '',
          id: ''
        },
        page: 1,
        pagesize: 20
      },
      selectData: [],
      list: [],
      total: 0,
      btnLoading: false,

      // 新增分类弹窗
      classifyFormialogVisible: false,
      classifyForm: { title: '', remark: '' },
      classifyFormRules: {
        title: [{ required: true, message: '请输入', trigger: 'blur' }]
      },

      // 药品导入弹窗的显示与否
      drugImportDialogVisible: false,
      fileList: [],
      uploadDisabled: true
    }
  },
  created() {
    this.getSelectData()
    this.getListData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'get_drdrug,get_drug_category'
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData = res.data
    },
    searchList() {
      this.queryInfo.page = 1
      this.getListData()
    },
    resetSearchForm() {
      //   console.log(this)
      this.$refs.searchFormRef.resetFields()
      this.getListData()
    },
    async getListData() {
      // 返回数据重命名为res
      const { data: res } = await this.$http.post(
        '/admin/drdrug/list',
        this.queryInfo
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      for (let i = 0; i < res.data.list.length; i++) {
        res.data.list[i].editPriceFlag = false
      }
      this.list = res.data.list
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getListData()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.page = newPage
      this.getListData()
    },
    async disable(row) {
      // 弹框询问是否关闭服务
      const confirmResult = await this.$confirm(
        '是否确认关闭该药品【' + row.id + '】？关闭后不能再使用',
        '关闭',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      const { data: res } = await this.$http.post('/admin/drdrug/active', {
        id: row.id,
        type: 'close'
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getListData()
    },
    async enable(id) {
      const { data: res } = await this.$http.post('/admin/drdrug/active', {
        id: id,
        type: 'active'
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getListData()
    },
    // async showLog(id) {
    //   const { data: res } = await this.$http.post(
    //     '/admin/dr_hospital_ser/getLog',
    //     {
    //       service_item_id: id
    //     }
    //   )

    //   this.logTableData = res.data
    //   //   接口请求数据
    //   this.logDialogVisible = true
    // },
    async downloadExcel() {
      this.btnLoading = true
      this.$http({
        method: 'post',
        url: '/admin/drdrug/export',
        data: this.queryInfo.query,
        headers: {
          token: window.sessionStorage.getItem('token')
        },
        responseType: 'blob'
      })
        .then((res) => {
          this.btnLoading = false
          if (res.data.type) {
            // 文件下载
            const blob = new Blob([res.data], {
              type: 'application/vnd.ms-excel'
            })
            let link = document.createElement('a')
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', '药品数据.xlsx')
            link.click()
            link = null
            this.$message.success('导出成功')
          } else {
            // 返回json
            this.$message.warning(res.data.msg)
          }
        })
        .catch((err) => {
          this.btnLoading = false
          this.$message.error(err)
        })
    },
    async downloadDrugTemplate() {
      this.btnLoading = true
      this.$http({
        method: 'post',
        url: '/admin/drdrug/downloadDrugTemplate',
        headers: {
          token: window.sessionStorage.getItem('token')
        },
        responseType: 'blob'
      })
        .then((res) => {
          this.btnLoading = false
          if (res.data.type) {
            // 文件下载
            const blob = new Blob([res.data], {
              type: 'application/vnd.ms-excel'
            })
            let link = document.createElement('a')
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', '药品导入模板.xlsx')
            link.click()
            link = null
            this.$message.success('下载成功')
          } else {
            // 返回json
            this.$message.warning(res.data.msg)
          }
        })
        .catch((err) => {
          this.btnLoading = false
          this.$message.error(err)
        })
    },
    addClassify() {
      // 校验数据
      this.$refs.classifyFormRef.validate(async (valid) => {
        if (!valid) return
        // 请求接口
        // 向后端发起请求
        const { data: res } = await this.$http.post(
          '/admin/drdrug_category/create',
          this.classifyForm
        )

        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('新增分类成功')
        this.classifyFormialogVisible = false
      })
    },
    fileChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]] // 展示最后一次选择的文件
        this.uploadDisabled = false
      }
    },
    beforeUploadFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      let size = file.size / 1024 / 1024
      if (extension !== 'xlsx') {
        this.$message.warning('只能上传后缀是.xlsx的文件')
      }
      if (size > 10) {
        this.$message.warning('文件大小不得超过10M')
      }
    },
    // 移除选择的文件
    fileRemove(file, fileList) {
      if (fileList.length < 1) {
        this.uploadDisabled = true //未选择文件则禁用上传按钮
      }
    },
    importExcel() {
      this.$refs.upload.submit()
    },
    async uploadHttpRequest(param) {
      // console.log(param)
      let form = new FormData()
      form.append('file', param.file)

      const { data: res } = await this.$http.post(
        '/admin/drdrug/importExcel',
        form
      )

      if (res.meta.status !== 200) {
        // return this.$message.error(res.meta.msg)
        return this.$alert(res.meta.msg, '错误提示', {
          confirmButtonText: '确定',
          type: 'error',
          callback: (action) => {
            this.fileList = []
            this.uploadDisabled = true
          }
        })
      }
      this.$message.success('药品导入成功' + res.data + '条')
      this.drugImportDialogVisible = false
      this.getListData()
    }
  },
  watch: {
    classifyFormialogVisible() {
      if (!this.classifyFormialogVisible) {
        this.$refs.classifyFormRef.resetFields()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.dialog-footer {
  text-align: center;
}
</style>
